const fs = require("fs");
const {logName} = require("./common");
const {notice} = require("../utils/util");

/**
 * notCreate 未创建
 * creating 创建中
 * success 创建成功
 * failure 创建失败
 */
let created = "notCreate";
const filename = logName.replace('.log', '.error.log');

function init() {
  created = 'success';
  notice(`错误日志输出到 ${filename}`);

  fs.writeFileSync(filename, `init..\n\n`, (err) => {
    if (err) {
      created = 'failure';
      notice('错误日志创建失败!!!', 'error')
    }
  })
}

/**
 *
 * @param {string} message
 * @return {?boolean} result
 */
function appendErrorLog(message) {
  switch (created) {
    case "notCreate": {
      init();
      return false;
    }
    case "creating": {
      return false;
    }
    case "failure": {
      notice(message, 'error');
      break;
    }
    case "success": {
      fs.appendFileSync(filename, message)
      break
    }
  }

  return true;
}

module.exports = appendErrorLog
